<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="classifyName">
        <el-cascader
          v-model="queryParams.classifyCodingName"
          :options="options"
          :props="countryObj"
          :show-all-levels="true"
          clearable
          placeholder="请选择分类"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in isShowOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否热卖" prop="whetherSelling">
        <el-select v-model="queryParams.whetherSelling" placeholder="请选择是否热卖" clearable size="small">
          <el-option
            v-for="dict in whetherSellingOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shopping:mallProduct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shopping:mallProduct:export']"
          v-if="false"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table class="dialog" v-loading="loading" :height="tableHeight" :data="mallProductList" >
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品主图" align="center" prop="productImage">
        <template width="120" slot-scope="scope">
          <img style="width:60px;height:60px;border:none;" :src="scope.row.productImage">
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="classifyName" />
      <el-table-column label="原价" align="center" prop="oldPrice" />
      <el-table-column label="售价" align="center" prop="currentPrice" />
      <el-table-column label="虚拟销量" align="center" prop="salesNum" />
      <el-table-column label="状态" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            class="showValue"
            active-value="Y"
            inactive-value="N"
            active-text="上架"
            inactive-text="下架"
            active-color="#1E90FF"
            inactive-color="#6E7B8B"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否热卖" align="center" prop="whetherSelling">
        <template slot-scope="scope">
          <dict-tag :options="whetherSellingOptions" :value="scope.row.whetherSelling"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-show="useEdit"
            v-if="scope.row.isShow == 'N'"
            v-hasPermi="['shopping:mallProduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-show="useEdit"
            v-if="scope.row.isShow == 'N'"
            v-hasPermi="['shopping:mallProduct:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleLookEvaluate(scope.row)"
            v-hasPermi="['shopping:mallProduct:remove']"
          >查看评价</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商城商品对话框 -->
    <el-dialog  class="dialog" :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px"   append-to-body>
      <div class="el-dialog-div">
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="100px">
        <el-form-item label="商品名称" prop="productName" >
          <el-input v-model="form.productName" placeholder="请输入商品名称"  maxlength="30"  />
        </el-form-item>
        <el-row>
          <el-form-item label="商品主视频" >
            <file-upload :isShowTip="false"  :limit="1"  :multiple="false"  :fileSize="1024" :fileType="videoFileType" v-model="form.productMainVideo"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="商品主图" prop="productImage">
            <imageUpload  :limit="1" :multiple="false" v-model="form.productImage"/>
          </el-form-item>
        </el-row>
        <el-row>

          <el-form-item label="商品副图"  placeholder="请选择上传图片">
            <imageUpload
              :limit="5"
              :multiple="true"
              :on-success="pictureSuccess"
              v-model="form.productDeputyImage"/>

<!--            <imageMultiple-->
<!--              v-if="showImgUpload"-->
<!--              v-model="form.productDeputyImage"-->
<!--              :picArr="picArr"-->
<!--              :limit="5"-->
<!--              @uploadADPic="uploadADPic"-->
<!--              @removeADPic="removeADPic"-->
<!--              ref="loadData"/>-->
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="商品详情">
            <editor v-model="form.richText" :height="300" :min-height="150" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="商品分类" prop="classifyId">
            <el-cascader
              :placeholder="form.classifyName"
              v-model="form.classifyCodingName"
              :options="options"
              :props="countryObj"
              :show-all-levels="false"
              :clearable = "true"
              @change="handleChange"
              ref="cascader"
            >
            </el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="是否热卖" prop="whetherSelling">
            <el-select v-model="form.whetherSelling" placeholder="请选择是否热卖">
              <el-option
                v-for="dict in whetherSellingOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="1" />
          </el-form-item>
        </el-row>

        <!--选择规格-->
        <el-table :data="form.dataValue" highlight-current-row style="text-align:center;width: 100%">
          <el-table-column prop="specsName" label="规格名称"  >
            <template slot-scope="scope" >
                <el-form-item :prop="'dataValue.'+scope.$index + '.specsName'" :rules='rules.specsName'>
                  <el-input  v-model.trim="scope.row.specsName" ></el-input>
                </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="specsPhoto" label="规格照片">
            <template slot-scope="scope">
              <el-form-item :prop="'dataValue.'+scope.$index + '.specsPhoto'" :rules='rules.specsPhoto'>
                <image-upload :isShowTip="false" :limit="1" :multiple="false"  v-model.number="scope.row.specsPhoto" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="originalPrice" label="原价">
            <template slot-scope="scope">
              <el-form-item :prop="'dataValue.'+scope.$index + '.originalPrice'" :rules='rules.originalPrice'>
<!--                <el-input type="number" v-model.number="scope.row.originalPrice"></el-input>\-->
                <el-input type="number" v-model="scope.row.originalPrice"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="currentPrice" label="现价">
            <template slot-scope="scope">
              <el-form-item :prop="'dataValue.'+scope.$index + '.currentPrice'" :rules='rules.currentPrice'>
                <el-input size="medium" type="number" v-model="scope.row.currentPrice"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="salesNum" label="虚拟销量">
            <template slot-scope="scope">
              <el-form-item :prop="'dataValue.'+scope.$index + '.salesNum'" :rules='rules.salesNum'>
                <el-input  v-model.number="scope.row.salesNum"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
              <el-button   type="danger" size="mini" @click="del(scope.$index)" icon='el-icon-delete'></el-button>
              <el-button   type="primary" size="mini" @click="add" icon='el-icon-plus'></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
  import ImageMultiple from '@/components/ImageMultipleUpload';
  import {editStatus,listMallProduct, getMallProduct, logicDelMallProduct, addMallProduct, updateMallProduct, exportMallProduct } from "@/api/shopping/mallProduct";
  import {getSpecsValue} from "@/api/shopping/mallProductSpecs";
  import {liststate } from "@/api/shopping/classify";
  export default {
    name: "MallProduct",
    components: {
      ImageMultiple,
    },
    data() {
      return {
        fileList:[],
        picStrArr:[],
        picArr:[],
        showImgUpload:false,
        //搜索中分类名称转换后的值
        classifyTransitionId:[],
        //修改商品规格中不能显示添加按钮
        useEdit:true,
        //选择分类的数据
        // 状态字典
        isShowOptions: [],
        classifyCodingName:[],
        options:[],
        tableHeight:0,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total:0,
        // 商城商品表格数据
        mallProductList:[],
        //商品规格数据
        mallProductSpecsList:[],
        // 是否热卖字典
        whetherSellingOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          productName: null,
          oldPrice:null,
          productMainVideo: null,
          productImage: null,
          isShow: null,
          productDeputyImage: null,
          classifyCodingName:null,
          richText: null,
          classifyId: null,
          whetherSelling:null,
          classifyName:null,
          sort: null,
          service: null,
          currentPrice: null,
          salesNum: null,
        },
        videoFileType:["mp4"],
        // 表单参数
        form: {
          dataValue:[
          ],
        },
        // 表单校验
        rules: {
          //规格系列校验
          productImage:[
            { required: true, message: '请上传商品主图', trigger: 'blur' }
          ],
          specsName: [
            { required: true, message: '请填写商品规格名称', trigger: 'blur' }
          ],
          specsPhoto:[
            { required: true, message: '请选择商品规格照片', trigger: 'blur' }
          ],
          originalPrice :[
            { required: true, message: '请填写商品规格原价', trigger: 'blur' }
          ],
          currentPrice :[
            { required: true, message: '请填写商品规格现价', trigger: 'blur' }
          ],
          salesNum :[
            { required: true, message: '请填写商品规格销量', trigger: 'blur' }
          ],
          //规格系列校验
          productName:[
            { required: true, message: '请填写商品名称', trigger: 'blur' }
          ],
          classifyId:[
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ],
          classifyCodingName:[
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ],
        },
        countryObj:{
          value:'id',
          label: 'classifyName',
          children: 'children',
          lazy: true,
          lazyLoad (node, resolve) {
            const { level } = node;
            let id = node.value;
            let param={id:id};
            liststate(param).then(response => {
              let options = response.rows;
              resolve(options);
            });
          }
        },
      };
    },
    beforeRouteEnter(to, form, next) {
      next(vm => {
        const isShow = vm.$route.query && vm.$route.query.isShow;
        vm.queryParams.isShow = isShow;
        vm.getList();
      });
    },
    created() {
      this.getList();
      this.calHeight();
      this.getDicts("sys_yes_no").then(response => {
        this.whetherSellingOptions = response.data;
      });
      this.getDicts("sys_isShow").then(response => {
        this.isShowOptions = response.data;
      });
    },
    watch: {
      'showSearch':'calHeight',
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },

      uploadADPic(data){
        this.picStrArr.push(data)
        // if (!this.picStrArr){
          this.form.productDeputyImage =  this.picStrArr.join(",")
        // }
      },
      removeADPic(data){
        for(var i = 0; i < this.picStrArr.length; i++){
          if(this.picStrArr[i] == data){
            this.picStrArr.splice(i,1)
          }
        }
      },

      pictureSuccess(response,file,fileList){
      },
      //选中开关是否上架
      handleStatusChange(date){
        let query={
          id : date.id,
          status:date.isShow
        }
        editStatus(query).then(response => {
          if (query.status=="Y"){
            this.msgSuccess("上架成功");
          }else if (query.status=="N"){
            this.msgSuccess("下架成功");
          }

        })

      },
      //查看商品评价
      handleLookEvaluate(row){
        this.$router.push({ path: '/shopping/comment', query: { id: row.id }})
      },
      add(){
        this.form.dataValue.push({
          productId:null,
          specsName:null,
          specsPhoto:null,
          sort:null,
          originalPrice:null,
          currentPrice: null,
          salesNum:null,
        })
      },
      del(index){
        //不能都删除，必须保留一个
        if (index!=0){
          this.form.dataValue.splice(index,1);
        }else {
          this.$message.error("无法删除！")
        }

      },
      //选择分类
      handleChange(value) {
        var node=this.$refs['cascader'].getCheckedNodes(true);
        if(node && node.length>0){
          this.form.classifyId = node[0].value;
          this.form.classifyName = node[0].label;
        }else{
          this.form.classifyId = null
          this.form.classifyName = null
        }
      },
      // 清空已经选中的数据方法
      clear() {
        this.$refs.cascader.$refs.panel.clearCheckedNodes();
        this.form.classifyName = "请输入分类"
      },
      calHeight () {
        this.$nextTick(() => {
          const rect = this.$refs.appcontainer.getBoundingClientRect();
          let height= this.$refs.queryForm.$el.offsetHeight;
          this.tableHeight = rect.height-height-120;
        })
      },
      /** 查询商城商品列表 */
      getList() {
        this.loading = true;
        if (this.queryParams.classifyCodingName!=null){
          let str = this.queryParams.classifyCodingName
          if(str.constructor== Array ){
            this.queryParams.classifyCodingName = str.join(",")
          }
        }
        listMallProduct(this.queryParams).then(response => {
          this.mallProductList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.showImgUpload = false
        this.$nextTick(function(){
          this.showImgUpload= true
        })
        // this.picArr = []
        // this.picStrArr = []

        this.form = {
          id: null,
          productName: null,
          productImage: null,
          productDeputyImage: null,
          productMainVideo: null,
          classifyName:'请选择分类',
          richText: null,
          sort: null,
          whetherSelling:"N",
          service: null,
          currentPrice: null,
          salesNum: null,
          delState: null,
          isShow:"N",
          oldPrice:null,
          delUser: null,
          delType: null,
          delTime: null,
          createBy: null,
          createType: null,
          createTime: null,
          updateBy: null,
          updateType: null,
          updateTime: null,
          dataValue:[
            { productId:"",
              specsName:"",
              specsPhoto:"",
              sort:"",
              originalPrice:"",
              currentPrice: "",
              salesNum: "",
            },
          ],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.showSearch=false;
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.classifyCodingName = null;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        console.error("aa"+this.form.productImage)
        console.error("bb"+this.form.productDeputyImage)
        debugger
        this.reset();
        this.form.classifyName = "请输入分类"
        this.open = true;
        this.title = "添加商城商品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getMallProduct(id).then(response => {
          this.title = "修改商城商品";
          if(response.data.productDeputyImage){
            var picArrs = response.data.productDeputyImage.split(",");
            this.picStrArr = picArrs
            this.picArr = []
            for (let i = 0; i< picArrs.length; i++){
              var obj = {};
              obj.url = picArrs[i];
              this.picArr.push(obj);
            }
          }
          this.form = response.data;
          let classifyCodingArr=new Array();
          let numArray = classifyCodingArr.map(Number);
          this.form.classifyCodingName=numArray;
          const query = {
            productId:row.id
          }
          getSpecsValue(query).then(response => {
            this.form.dataValue = response.rows;
          });
          this.open = true;
        });
      },
      /** 提交按钮 */
      submitForm() {
        if (!this.form.classifyId){
          this.msgError("商品分类不能为空")
          return;
        }
        this.$refs["form"].validate(valid => {
          // debugger
          // console.info("this.form.classifyCodingName"+this.form.classifyCodingName);
          // if ( null == this.form.classifyCodingName){
          //   return
          // }
          if (valid) {
            this.form.classifyCodingName = this.form.classifyCodingName.join(",");
            if (this.form.id != null) {
              updateMallProduct(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(res=>{
              });
            } else {
              addMallProduct(this.form).then(response => {
                this.msgSuccess("新增成功");
                // 新增商品规格
                this.open = false;
                this.clear();
                this.getList();

              }).catch(res=>{
                });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return logicDelMallProduct(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商城商品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      }
    }

  };

</script>

<style scoped  >
 .el-dialog-div{
    height: 60vh;
    overflow: auto;
  }
 .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
  }
  /*打开时文字位置设置*/
.el-switch__label--right {
    z-index: 1;
    right: 8px;
  }
  /*关闭时文字位置设置*/
 .el-switch__label--left {
    z-index: 1;
    left: 8px;
  }
  /*显示文字*/
  .el-switch__label.is-active {
    display: block;
  }
 .el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 50px !important;
  }
 /deep/ .el-upload--picture-card{
   width: 60px;
   height: 60px;
   line-height: 66px;
 }
 /deep/ .el-upload-list--picture-card .el-upload-list__item{
   width: 60px;
   height: 60px;
   margin: 0;
 }
 /deep/ .el-upload-list__item-status-label{
   display: none;
 }
   .component-upload-image el-upload-list--picture-card{
    margin: 0;
  }
  .component-upload-image .hide{
    height: 60px;
  }
 .el-dialog-div .el-button{
    margin-bottom: 20px;
  }
</style>


<style>

</style>
